package org.example.myleet.p1583;

import java.util.*;

public class Solution {
    public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
        int[][] friendlyMapArr = new int[n][n];
        for (int i = 0; i < preferences.length; ++i) {
            int distance = 1;
            int[] friendlyMap = new int[n];
            Arrays.fill(friendlyMap, Integer.MIN_VALUE);
            for (int friend : preferences[i]) {
                friendlyMap[friend] = distance;
                ++distance;
            }
            friendlyMapArr[i] = friendlyMap;
        }
        Set<Integer> unhappy = new HashSet<>(n);
        for (int i = 0; i < pairs.length; ++i) {
            int[] pairXY = pairs[i];
            for (int j = i + 1; j < pairs.length; ++j) {
                int[] pairUV = pairs[j];
                if (isUnhappy(pairXY[0], pairXY[1], pairUV[0], pairUV[1], friendlyMapArr)) {
                    unhappy.add(pairXY[0]);
                    unhappy.add(pairUV[0]);
                }
                if (isUnhappy(pairXY[1], pairXY[0], pairUV[0], pairUV[1], friendlyMapArr)) {
                    unhappy.add(pairXY[1]);
                    unhappy.add(pairUV[0]);
                }
                if (isUnhappy(pairXY[0], pairXY[1], pairUV[1], pairUV[0], friendlyMapArr)) {
                    unhappy.add(pairXY[0]);
                    unhappy.add(pairUV[1]);
                }
                if (isUnhappy(pairXY[1], pairXY[0], pairUV[1], pairUV[0], friendlyMapArr)) {
                    unhappy.add(pairXY[1]);
                    unhappy.add(pairUV[1]);
                }
            }
        }
        return unhappy.size();
    }

    private boolean isUnhappy(int x, int y, int u, int v, int[][] friendlyMapArr) {
        int distanceXU = friendlyMapArr[x][u];
        int distanceXY = friendlyMapArr[x][y];
        int distanceUX = friendlyMapArr[u][x];
        int distanceUV = friendlyMapArr[u][v];
        if (distanceXU < distanceXY) {
            return distanceUX < distanceUV;
        }
        return false;
    }
}
